package com.tanhua.manage.service;

import com.tanhua.manage.config.HuaWeiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author guzi
 * @date 2021/1/13
 */
@Service
public class HuaWeiService {

    public static final String REDIS_KEY="HUAWEI_TOKEN";

    @Autowired
    private HuaWeiConfig huaWeiConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${huaweicloud.moderation.categories.text}")
    private String CATEGORIES_TEXT;

    @Value("${huaweicloud.text.check.url}")
    private String TEXT_CHECK_URL;

    @Value("${huaweicloud.moderation.categories.image}")
    private String CATEGORIES_IMAGE;

    @Value("${huaweicloud.image.check.url}")
    private String IMAGE_CHECK_URL;


    /**
     * 获取 token
     * @return
     */
    public String getHuaWeiToken(){

        //先从 redis里查 token,如果有就直接返回
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if (null != token){
            return token;
        }

        //如果 redis中没有 token

        //设置访问url
        String targetUrl = this.huaWeiConfig.getUrl();

        //设置请求头
        HttpHeaders header = new HttpHeaders();
        header.set("Content-Type", "application/json");

        //设置请求体
        String body = "{ \n" +
                "    \"auth\": { \n" +
                "        \"identity\": { \n" +
                "            \"methods\": [ \n" +
                "                \"password\" \n" +
                "            ], \n" +
                "            \"password\": { \n" +
                "                \"user\": { \n" +
                "                    \"name\": \"" + this.huaWeiConfig.getName() + "\", \n" +
                "                    \"password\": \""+ this.huaWeiConfig.getPassword() +"\", \n" +
                "                    \"domain\": { \n" +
                "                        \"name\": \"" + this.huaWeiConfig.getDomain() +"\" \n" +
                "                    } \n" +
                "                } \n" +
                "            } \n" +
                "        }, \n" +
                "        \"scope\": { \n" +
                "            \"project\": { \n" +
                "                \"name\": \""+ this.huaWeiConfig.getProject() +"\" \n" +
                "            } \n" +
                "        } \n" +
                "    } \n" +
                "}";


        HttpEntity<String> httpEntity = new HttpEntity<>(body, header);

        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, String.class);


        if(responseEntity.getStatusCodeValue()!=201){
            return null;
        }

        //如果查询到就放到 redis缓存,有效期为23小时
        token = responseEntity.getHeaders().get("X-Subject-Token").get(0);
        redisTemplate.opsForValue() .set(REDIS_KEY, token, 60*60*23, TimeUnit.SECONDS);

        return token;
    }

    /**
     * 文字审核
     *
     * @param text
     * @return
     */
    public String auditText(String text){
        //获取token
        String token = this.getHuaWeiToken();

        //设置访问url
        String targetUrl = TEXT_CHECK_URL;

        //设置请求头
        HttpHeaders header = new HttpHeaders();
        header.set("Content-Type", "application/json");
        header.set("X-Auth-Token", token);

        //设置请求体
        String body = "{\n" +
                "   \"categories\":[\"ad\",\"politics\",\"abuse\",\"porn\",\"contraband\",\"flood\"],\n" +
                "   \"items\":[\n" +
                "      {\n" +
                "          \"text\": \"" + text + "\",\n" +
                "          \"type\": \"content\"\n" +
                "      }\n" +
                "    ]\n" +
                "}";

        //请求API
        HttpEntity<String> httpEntity = new HttpEntity<>(body, header);
        ResponseEntity<String> responseEntity;
        try{
            responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, String.class);
        }catch (Exception e){
            e.printStackTrace();
            return "review";
        }

        //检验是否请求成功
        if (200 != responseEntity.getStatusCodeValue()){
            return "review";
        }

        //返回结果
        String result = responseEntity.getBody();
        if (result.contains("review")){
            return "review";
        }else if (result.contains("block")){
            return "block";
        }else{
            return "pass";
        }

        //如果想要所有信息那么返回responseEntity给调用者处理
        //return responseEntity;
    }

    /**
     * 图片审核
     *
     * @param images
     * @return
     */
    public String auditImage(String[] images){
        //获取token
        String token = this.getHuaWeiToken();

        //设置访问url
        String targetUrl = IMAGE_CHECK_URL;

        //设置请求头
        HttpHeaders header = new HttpHeaders();
        header.set("Content-Type", "application/json");
        header.set("X-Auth-Token", token);

        //拆分images
        String imageItem = "";
        for (String image : images) {
            imageItem += "\"" + image + "\",";
        }
        imageItem = imageItem.substring(0, imageItem.length() - 1);

        //设置请求体
        String body = "{  \n" +
                "   \"urls\": [" + imageItem + "],\n" +
                "   \"categories\":[  \n" +
                "      \"politics\",\n" +
                "      \"terrorism\",\n" +
                "      \"porn\"],\n" +
                "   \"threshold\" : \"\"\n" +
                "}";

        //请求API
        HttpEntity<String> httpEntity = new HttpEntity<>(body, header);
        ResponseEntity<String> responseEntity;
        try{
            responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, String.class);
        }catch (Exception e){
            e.printStackTrace();
            return "review";
        }

        //检验是否请求成功
        if (200 != responseEntity.getStatusCodeValue()){
            return "review";
        }

        //返回结果
        String result = responseEntity.getBody();
        if (result.contains("review")){
            return "review";
        }else if (result.contains("block")){
            return "block";
        }else{
            return "pass";
        }

        //如果想要所有信息那么返回responseEntity给调用者处理
        //return responseEntity;
    }
}
